<template>
  <div>
    <el-form v-if="showMode=='table'" :model="vo" class="attachments-container" :style="{'margin-top':showMode === 'list'?'-1px':'20px'}">
      <div class="el-table el-table--fit el-table--border" :style="{'z-index':showMode === 'list'?2:''}">
        <div
          class="el-table__body-wrapper"
          :class="{fileHovering:fileHovering}"
          @dragenter.capture="handleFileDragEnter($event)"
          @dragleave.capture="handleFileDragLeave($event)"
          @dragover.capture="handleFileDragOver($event)"
          @drop.capture="handleFileDrop($event)"
        >
          <table class="el-table__body" cellspacing="0" cellpadding="0" border="0">
            <tbody>
              <tr>
                <td style="text-align: left;">
                  <el-upload
                    v-show="curTN.tnCanEdit===1&&canUpload"
                    ref="upload"
                    style="float:left;padding-right:4px;"
                    action=""
                    :on-change="handleUploadChange"
                    :on-error="handleUploadError"
                    :on-exceed="handleUploadExceed"
                    :multiple="true"
                    :limit="limitCount"
                    :file-list="uploadAttach"
                    :show-file-list="false"
                    :auto-upload="false"
                    :with-credentials="true"
                    :disabled="isOpenFile"
                  >
                    <el-button size="mini" style="border:0px;" @click="openFileBefore"> <svg-icon icon-class="add" style="color:green" />{{ uploadBtnName }}</el-button>
                  </el-upload>
                  <el-button v-show="curTN.tnCanEdit===1&&canDelete" size="mini" style="border:0px;" @click="handleUploadRemove()">
                    <svg-icon icon-class="remove" style="color:red" />{{ deleteBtnName }}</el-button>
                  <el-button size="mini" style="border:0px;" @click="handleFileDownload()">
                    <svg-icon icon-class="download" :style="'color:'+lightBlue" />{{ saveasBtnName }}</el-button>
                </td>
              </tr>
            </tbody>
          </table>
          <div v-if="showMode=='table'">
            <table v-if="showMode=='table'" class="el-table__body" cellspacing="0" cellpadding="0" border="0">
              <tbody id="output_area">
                <tr>
                  <td style="width:45px;text-align:center;">
                    <el-checkbox v-model="checkall" name="checkall" @change="checkAll" />
                  </td>
                  <td style="width:45px;text-align:center;">序号</td>
                  <td>文件名</td>
                  <td style="width:100px;text-align:center;">文件大小</td>
                  <td style="width:140px;text-align:center;">上传时间</td>
                  <td style="width:80px;text-align:center;">上传人</td>
                  <td v-if="(curTN.tnCanEdit===1&&onlineEditor!=='')||showDownloadLink" style="text-align:center;" :style="operateColWidth">操作</td>
                </tr>
              </tbody>
            </table>

            <table class="el-table__body wflow-attach" cellspacing="0" cellpadding="0" border="0">
              <tbody id="output_area" class="atach-draggable">
                <template v-if="updateAttachList">
                  <template v-for="(attach,index) in attachments.filter((obj)=>obj.fileType===attachsType)">
                    <tr :key="index" :class="{'drag-handler':isSortAttach}">
                      <td style="width:45px;text-align: center;cursor:auto;" align="center">
                        <el-checkbox v-model="attach.checked" name="checkbox" @change="attachCheckedChange" />
                      </td>
                      <td style="width:45px;text-align: center;cursor:auto;">{{ index+1 }}</td>
                      <td style="cursor:auto;">
                        <el-tooltip class="item" effect="dark" :content="attach.fileName" placement="bottom-start">
                          <el-link type="primary" class="attach-name" @click="handleUploadPreview(attach)">{{ attach.fileName }}</el-link>
                        </el-tooltip>
                      </td>
                      <td style="width:100px;text-align: center;" :title="isSortAttach?'按下鼠标拖可动排序':''">
                        {{ attach.fileSize }}
                      </td>

                      <template v-if="attach.id">
                        <td style="width:140px;text-align: center;" :title="isSortAttach?'按下鼠标拖可动排序':''">
                          {{ attach.uploadTime }}
                        </td>
                        <td style="width:80px;" :title="isSortAttach?'按下鼠标拖可动排序':''">
                          <el-tooltip :disabled="attach.uploadBy.length<=5" class="item" effect="dark" :content="attach.uploadBy" placement="top">
                            <div style="width:100%;text-align: center;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">{{ attach.uploadBy }}</div>
                          </el-tooltip>
                        </td>

                        <td v-if="(curTN.tnCanEdit===1&&onlineEditor!=='')||showDownloadLink" :style="operateColWidth" style="text-align: center;cursor:auto;">
                          <el-link v-if="curTN.tnCanEdit===1&&onlineEditor!==''" :title="attach.canModify?'编辑':''" :disabled="!attach.canModify" @click="handleOpenEditor(attach)"><i :class="'el-icon-edit'" style="font-size:16px;" /></el-link>
                          <template v-if="curTN.tnCanEdit===1&&canDelete">
                            &nbsp;
                            <el-link :title="'删除'" type="danger" @click="handleUploadRemove(attach)"><i :class="'el-icon-close'" style="color:#ff0000;font-size:16px;" /></el-link>
                          </template>
                          <template v-if="showDownloadLink">
                             &nbsp;
                            <el-link :title="'下载'" @click="handleOneFileDownload(attach)"><i :class="'el-icon-download'" style="font-size:16px;" /></el-link>
                          </template>
                        </td>
                      </template>

                      <td v-else style="width:321px" colspan="3">
                        <el-progress v-if="!attach.file.message" :text-inside="true" :stroke-width="20" :percentage="attach.file.progress" status="success" />
                        <div v-if="attach.file.message" style="color:#ff0000;width: 100%;">
                          {{ attach.file.message }}
                        </div>
                      </td>
                    </tr>
                  </template>
                </template>
                <tr v-if="!hasAttachment">
                  <td style="width:45px;text-align: center;"><input type="checkbox" disabled="true"></td>
                  <td style="width:45px;text-align: center;" />
                  <td />
                  <td style="width:100px;text-align: center;" />
                  <td style="width:140px;text-align: center;" />
                  <td style="width:80px;text-align: center;" />
                  <td v-if="(curTN.tnCanEdit===1&&onlineEditor!=='')||showDownloadLink" style="text-align: center;" :style="operateColWidth" />
                </tr>
              </tbody>
            </table>
          </div>

        </div>
      </div>
    </el-form>
    <div
      v-else
      :class="{fileHovering:fileHovering}"
      @dragenter.capture="handleFileDragEnter($event)"
      @dragleave.capture="handleFileDragLeave($event)"
      @dragover.capture="handleFileDragOver($event)"
      @drop.capture="handleFileDrop($event)"
    >
      <el-upload
        v-show="curTN.tnCanEdit===1&&canUpload&&!isOpenFile"
        ref="upload"
        style="float:left;padding-right:4px;"
        action=""
        :on-change="handleUploadChange"
        :on-error="handleUploadError"
        :on-exceed="handleUploadExceed"
        :multiple="limitCount>1"
        :limit="limitCount"
        :file-list="uploadAttach"
        :show-file-list="false"
        :auto-upload="false"
        :with-credentials="true"
      >
        <el-button size="mini" @click="openFileBefore"> <svg-icon icon-class="add" style="color:green" />添加附件</el-button>
      </el-upload>
      <span v-show="curTN.tnCanEdit===1&&canUpload&&!isOpenFile">&nbsp;</span>
      <el-row v-for="(attach,index) in attachments.filter((obj)=>obj.fileType===attachsType)" :key="index" class="attach-row" align="middle">
        <el-col span="24" style="overflow: hidden;">
          <div style="float:left;font-size:16px;margin-right:5px;" :style="{'line-height':!attach.id?'22px':''}">
            <i class="el-icon-document" />
          </div>
          <div v-if="attach.id" style="width: calc(100% - 22px);float:left">
            <div style="float:left;width: calc(100% - 125px);">
              <el-link type="primary" class="attach-name" :title="attach.fileName" style="margin-top:-3px;max-width:calc(100% - 100px);" @click="handleUploadPreview(attach)">{{ attach.fileName }} </el-link>
              <span style="color:#a7a7a7;padding-left:5px;padding-right:5px;">{{ attach.fileSize }}</span>
              <el-link v-if="curTN.tnCanEdit===1&&onlineEditor!==''" :title="attach.canModify?'编辑':''" :disabled="!attach.canModify" @click="handleOpenEditor(attach)"><i :class="'el-icon-edit'" style="font-size:16px;" /></el-link>
              <el-link v-show="curTN.tnCanEdit===1&&canDelete" :underline="false" style="margin-top:-5px;" @click="handleUploadRemove(attach)"> <svg-icon icon-class="remove" style="color:red" /></el-link>
            </div>
            <span style="color:#a7a7a7;float:right">{{ attach.uploadTime }}</span>
          </div>
          <div v-else style="width: calc(100% - 22px);float:left;">
            <div style="line-height: 21px;width:100%;">
              <div class="attach-name" style="float:left;max-width: calc(100% - 113px)">
                <span style="display:block;">{{ attach.fileName }}</span>
              </div>
              <span style="color:#a7a7a7;padding-left:5px;padding-right:5px;">{{ attach.fileSize }}</span>
              <el-link v-show="attach.file.progress==0" :underline="false" style="margin-top:-5px;" @click="handleUploadRemove(attach)"> <svg-icon icon-class="remove" style="color:red;" /></el-link>
            </div>
            <el-progress v-if="!attach.file.message" :color="'#409eff'" style="margin:0px auto;" :percentage="attach.file.progress" :status="attach.file.progress==100?'success':''" />
            <div v-if="attach.file.message" class="attach-name" style="color:#ff0000;width: 100%;overflow: hidden;">
              <span> {{ attach.file.message }}</span>
            </div>
          </div>
        </el-col>
      </el-row>
      <el-row v-if="attachments.length==0" class="no-attachments">
        <el-col span="24" style="padding:15px 0 15px 0;">
          暂无附件
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
const imgType = ['png', 'jpg', 'gif', 'jpeg', 'webp', 'ico', 'jfif', 'bmp']

import variables from '@/wapp/common/styles/variables.scss'
import { mapGetters } from 'vuex'
import { formatFileSize } from '@/global/utils/index'
import Sortable from 'sortablejs'

let _this = null
export default {
    name: 'Attachment',
    components: {

    },
    props: {
        vo: { type: Object, default: function() { return {} } },
        curTN: { type: Object, default: function() { return {} } },
        flBodyfile: { type: Object, default: function() { return { file: { name: '' }} } },
        attachments: { type: Array, default: function() { return [] } }, // 已上传文件
        batchSaveNamefield: { type: String, default: '' }, // 批量下载时另存为文件名称
        wfAttachUrl: { type: String, default: '' },
        onlineFile: { type: String, default: '' }, // doc转pdf在线预览文件格式
        viewer: { type: String, default: 'pdfjs' }, // 在线预览文件方式
        viewerUrlParams: { type: String, default: '' }, // 在线预览额外参数添加
        canEdit: { type: Number, default: null },
        limitCount: { type: Number, default: 100 },
        isRequired: { type: Number, default: 0 }, // 是否至少上传一个
        attachsType: { type: String, default: 'ATTACH' },
        isSortAttach: { type: Boolean, default: false }, // 是否可以进行附件排序
        uploadBtnName: { type: String, default: '添加文件' },
        saveasBtnName: { type: String, default: '另存文件' },
        deleteBtnName: { type: String, default: '删除文件' },
        attachEdit: { type: Object, default: null },
        onlineEditor: { type: String, default: '' }, // 在线编辑器，默认为空，支持wpsh5、yzh5、ech5
        waterMark: { type: Boolean, default: false },
        markContent: { type: String, default: '' },
        sameNameBodyfile: { type: Boolean, default: true }, // 是否与正文文件同名
        showDownloadLink: { type: Boolean, default: false }// 是否提供列操作"下载"链接
    },
    data() {
        return {
            lightBlue: variables.lightBlue,
            uploadAttach: [], // 选择待上传文件
            checkall: false,
            fileHovering: false,
            isOpenFile: false,
            canUpload: true,
            canDelete: true,
            showMode: 'table', // 附件控件显示模式，table:表格模式，list：列表模式
            sortable: null,
            sortDrags: false, // 是否是附件内部拖拽排序
            updateAttachList: true,
            operateColWidth: 'width:100px'// 操作列宽度
        }
    },
    computed: {
        hasAttachment() {
            const hasAttachment = this.attachments.some(attach => {
                return attach.fileType === this.attachsType
            })

            return hasAttachment
        },
        ...mapGetters([
            'loginUser'
        ])
    },
    watch: {
        uploadAttach(val) {
            const filelength = this.attachments.filter((obj) => obj.fileType === this.attachsType).length
            const attachLength = this.attachments.filter((obj) => obj.fileType === this.attachsType && obj.id).length
            if (filelength > this.limitCount) {
                if (this.attachments.filter((obj) => obj.fileType === this.attachsType && obj.id).length > 0) {
                    this.$message.warning(`当前限制上传 ${this.limitCount} 个文件，已上传了 ${attachLength} 个文件，本次选择了 ${val.length} 个文件，已超出 ${filelength - this.limitCount} 个文件`)
                } else {
                    this.$message.warning(`当前限制上传 ${this.limitCount} 个文件，本次选择了 ${val.length} 个文件，共有 ${filelength} 个文件`)
                }
                this.uploadAttach = []
                this.attachments.splice(-1, val.length)
                this.isOpenFile = false
                return
            }
        },
        attachments: {
            handler(val) {
                if (val.filter((obj) => obj.fileType === this.attachsType).length >= this.limitCount) {
                    this.isOpenFile = true
                } else {
                    this.isOpenFile = false
                }

                if (this.attachments.length > 0) {
                    const imgViewList = []
                    let imgIndex = 0
                    let wfAttachUrl = this.wfAttachUrl
                    if (this.wfAttachUrl === '' && this.$vnode.context.moduleInfo) {
                        wfAttachUrl = this.$vnode.context.moduleInfo.insertUrl.replace('/insert', '')
                    }

                    this.attachments.forEach(item => {
                        if (item.fileType === this.attachsType && window.openImgView && item.id && imgType.indexOf(item.fileName.substr(item.fileName.lastIndexOf('.') + 1).toLowerCase()) > -1) {
                            item.downLoadPath = process.env.VUE_APP_BASE_API + '/' + wfAttachUrl + '/downloadById?inline=true&attachIds=' + item.id + '&topdf=false&httpPort=' + location.port
                            item.index = imgIndex
                            imgViewList.push(item)
                            imgIndex++
                        }

                        let extName = ''
                        if (item.fileName.indexOf('.') !== -1) {
                            extName = item.fileName.substring(item.fileName.lastIndexOf('.')).toLowerCase()
                            if (extName !== '' && (this.onlineFile + ',').indexOf(extName + ',') !== -1) {
                                item.canModify = true
                            }
                        }
                    })

                    if (window.openImgView) {
                        sessionStorage.setItem('IMG_VIEW_LIST_' + this.vo.id, JSON.stringify(imgViewList))
                    }
                }
            },
            immediate: true
        },
        canEdit(val) {
            this.$set(this.curTN, 'tnCanEdit', val)
        },
        curTN: {
            handler(val) {
                this.setCurTN()
            },
            deep: true
        }
    },
    created() {
        _this = this
        if (!this.limitCount) this.limitCount = 100
    },
    beforeDestroy() {

    },
    mounted() {
        this.setCurTN()

        // 添加到basicform组件管理的附件组件数组中，实现一个表单多个附件组件可正常上传功能
        const refsAttachments = this.$vnode.context.$parent.refsAttachments || this.$vnode.context.$parent.$vnode.context.refsAttachments
        if (refsAttachments && this.$vnode.context.canEdit === 1) {
            refsAttachments.push(this)
        }
    },
    methods: {
        bindDraggable() {
            const el = document.querySelector('.attachments-container .wflow-attach tbody')
            if (el !== null) {
                this.sortable = Sortable.create(el, {
                    handle: '.drag-handler',
                    dragClass: 'sortable-drag',
                    setData: function(dataTransfer) {
                        dataTransfer.setData('Text', '')
                    },
                    onChoose: () => {
                        _this.sortDrags = true
                    },
                    onEnd: evt => {
                        const attachs = _this.attachments.filter(attach => {
                            if (attach.fileType === this.attachsType) return true
                        })
                        const attacrow = attachs[evt.oldIndex]
                        if (!attacrow) return

                        attachs.splice(evt.oldIndex, 1)
                        attachs.splice(evt.newIndex, 0, attacrow)

                        _this.attachments.forEach(attach => {
                            if (attach.fileType !== this.attachsType) {
                                attachs.push(attach)
                            }
                        })

                        const sortedAttachs = attachs.filter(attach => {
                            if (attach.fileType === this.attachsType) return true
                        })

                        if (this.$vnode.context && this.$vnode.context.wfInstance) {
                            const parent = this.$vnode.context
                            parent.$set(parent.wfInstance.passenger, 'sortedAttachs', sortedAttachs)
                        }

                        _this.sortDrags = false
                        _this.updateAttachList = false
                        _this.$nextTick(() => {
                            _this.attachments = attachs
                            _this.updateAttachList = true
                        })
                    }
                })
            }
        },
        setCurTN() {
            if (this.curTN.tnCanEdit !== undefined) {
                // 流程表彰
                this.showMode = 'table'
                const tnAttachEdit = (this.curTN.tnAttachEdit || '').split(',')
                if (tnAttachEdit.length === 3) {
                    this.canUpload = (tnAttachEdit[0] === '1')
                    this.canDelete = (tnAttachEdit[2] === '1')
                }

                setTimeout(() => {
                    this.isSortAttach = this.isSortAttach && (this.curTN.tnCanEdit === 1)
                    if (this.isSortAttach && this.hasAttachment) {
                        this.bindDraggable()
                    }
                }, 200)
            } else if (this.curTN.tnCanEdit === undefined) {
                // 非流程表单
                this.showMode = 'list'

                if (this.attachEdit !== null) {
                    if (this.attachEdit.canUpload !== '' && this.attachEdit.canUpload !== null && this.attachEdit.canUpload !== undefined) this.canUpload = this.attachEdit.canUpload
                    if (this.attachEdit.canDelete !== '' && this.attachEdit.canDelete !== null && this.attachEdit.canDelete !== undefined) this.canDelete = this.attachEdit.canDelete
                }

                this.curTN.tnCanEdit = this.canEdit || this.$vnode.context.canEdit
                this.$vnode.context.$attachments = this

                if (this.wfAttachUrl === '' && this.$vnode.context.moduleInfo) {
                    this.wfAttachUrl = this.$vnode.context.moduleInfo.insertUrl.replace('/insert', '')
                }
            }
            const attachContainer = document.querySelector('.attachments-container')
            if (attachContainer !== null) {
                if (this.showMode === 'list') {
                    attachContainer.style.marginTop = '-1px'
                    attachContainer.querySelector('.el-table--border').style.zIndex = 2
                } else {
                    attachContainer.style.marginTop = '20px'
                }
            }

            if ((this.curTN.tnCanEdit !== 1 || this.onlineEditor === '') && this.showDownloadLink) {
                this.operateColWidth = 'width:80px;'
            } else {
                this.operateColWidth = 'width:100px;'
            }
        },
        // 文件进入事件
        handleFileDragEnter(e) {
            if (_this.sortDrags) return
            e.stopPropagation()
            e.preventDefault()
            this.fileHovering = true
        },
        // 文件离开事件
        handleFileDragLeave(e) {
            if (_this.sortDrags) return
            e.stopPropagation()
            e.preventDefault()
            this.fileHovering = false
        },
        // 文件拖拽完成效果
        handleFileDragOver(e) {
            if (_this.sortDrags) return
            e.stopPropagation()
            e.preventDefault()
            e.dataTransfer.dropEffect = 'copy'
            this.fileHovering = true
        },
        openFileBefore() {
            if (this.isOpenFile) {
                this.$message.warning(`当前限制上传 ${this.limitCount} 个文件，不允许在添加新文件`)
            }
        },
        // 文件拖拽到页面后处理方式
        handleFileDrop(e) {
            if (_this.sortDrags) return
            e.stopPropagation()
            e.preventDefault()
            this.fileHovering = false
            const files = e.dataTransfer.files
            for (var j = 0; j < this.attachments.length; j++) {
                for (let i = 0; i < files.length; i++) {
                    const file = files[i]
                    if (file.name === this.attachments[j].fileName && (this.attachments[j].fileType === this.attachsType || (!this.sameNameBodyfile && this.attachments[j].fileType === 'BODY'))) {
                        this.$message.error('文件“' + file.name + '”已存在，不允许上传命名文件。')
                        return
                    }
                }
            }

            for (const fileItem of files) {
                this.attachments.push(
                    {
                        fileName: fileItem.name,
                        fileSize: formatFileSize(fileItem.size),
                        fileType: this.attachsType,
                        uploadBy: this.loginUser.personName,
                        uploadTime: '待上传',
                        file: { raw: fileItem, name: fileItem.name, size: fileItem.size },
                        checked: false,
                        progress: 0
                    }
                )
            }
        },
        checkAll() {
            this.attachments.forEach(attach => {
                if (attach.fileType === this.attachsType) {
                    attach.checked = this.checkall
                }
            })
        },
        attachCheckedChange() {
            let checkedAll = true
            this.attachments.forEach(attach => {
                if (!attach.checked && attach.fileType === this.attachsType) {
                    checkedAll = false
                }
            })
            this.checkall = checkedAll
            this.$forceUpdate()
        },
        handleUploadPreview(attach) {
            if (attach.id === undefined) return
            let extName = ''
            let topdf = false
            if (attach.fileName.indexOf('.') !== -1) {
                extName = attach.fileName.substring(attach.fileName.lastIndexOf('.')).toLowerCase()
                if (extName !== '.pdf' && extName !== '.pdfx' && (this.onlineFile + ',').indexOf(extName + ',') !== -1) {
                    topdf = true
                }
            }

            if (this.viewer.indexOf('dcs=') === 0 && (topdf || extName === '.pdf' || extName === '.pdfx' || extName === '.ofd')) {
                this.$http({
                    method: 'GET',
                    url: 'base/user/getSessionId'
                }).then(res => {
                    if (res.code === 'success') {
                        const tSessionId = res.body.tSessionId
                        const hostname = location.href.split('#')[0]
                        let downUrl = hostname.substring(0, hostname.length - 1) + process.env.VUE_APP_BASE_API + '/' + this.wfAttachUrl + '/downloadById?attachIds=' + attach.id + '&httpPort=' + location.port + '&tSessionId=' + tSessionId

                        let convertType = '0'
                        if (extName === '.pdf') {
                            convertType = '20'
                        } else if (extName === '.ofd') {
                            convertType = '21'
                        }

                        downUrl = this.viewer.split('=')[1] + '/composite/httpfile?convertType=' + convertType + '&fileUrl=' + encodeURIComponent(downUrl + (this.waterMark ? ('&waterMark=' + this.waterMark + '&markContent=' + this.markContent) : ''))
                        if (this.viewerUrlParams !== '' && this.viewerUrlParams !== null && this.viewerUrlParams !== undefined) {
                            downUrl += this.viewerUrlParams
                        }
                        this.$bus.emit('showDoingDialog', '正在生成在线预览文件，请稍候...')
                        $.post(downUrl, { }, res => {
                            this.$bus.emit('closeDoingDialog')
                            if (res.errorcode === 0) {
                                window.open(res.data.viewUrl)
                            } else {
                                this.$alert(res.message, '操作提示', { type: 'error' })
                            }
                        }, 'json')
                    }
                })
            }  else if (this.viewer === 'wpsjs' ) {
                this.$bus.emit('btnPreviewAttachClick', attach, this.onlineEditor)
            }else {
                if (imgType.indexOf(extName.substr(1)) > -1 && window.openImgView) {
                    sessionStorage.setItem('IMG_INDEX_' + this.vo.id, attach.index)
                    window.open('#/imgView?wfAttachUrl=' + this.wfAttachUrl + '&busiDataId=' + this.vo.id)
                    return
                }
                let downUrl = process.env.VUE_APP_BASE_API
                downUrl += (this.wfAttachUrl.substr(0, 1) === '/' ? this.wfAttachUrl : ('/' + this.wfAttachUrl))
                downUrl += '/downloadById?inline=true&attachIds=' + attach.id + '&topdf=' + topdf
                downUrl += (this.waterMark ? ('&waterMark=' + this.waterMark + '&markContent=' + this.markContent) : '')
                downUrl += '&httpPort=' + location.port

                window.open(downUrl)
            }
        },
        handleUploadExceed(files, fileList) {
            console.log('handleUploadExceed' + files)
            // this.$message.warning(`当前限制选择 ${this.limitCount} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
            const attachLength = this.attachments.filter((obj) => obj.fileType === this.attachsType && obj.id).length
            const filelength = attachLength + files.length + fileList.length
            if (this.attachments.filter((obj) => obj.fileType === this.attachsType && obj.id).length > 0) {
                this.$message.warning(`当前限制上传 ${this.limitCount} 个文件，已上传了 ${attachLength} 个文件，本次选择了 ${files.length} 个文件，已超出 ${filelength - this.limitCount} 个文件`)
            } else {
                this.$message.warning(`当前限制上传 ${this.limitCount} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${filelength} 个文件，已超出 ${filelength - this.limitCount} 个文件`)
            }
        },
        handleUploadRemove(file, fileList) {
            let attachIds = ''
            for (var i = 0; i < this.attachments.length; i++) {
                if (file !== undefined) {
                    if (this.attachments[i].forward && file.id === this.attachments[i].id) {
                        this.attachments.splice(i--, 1)
                    } else if (file.file !== undefined && file.file === this.attachments[i].file) {
                        for (let j = 0; j < this.uploadAttach.length; j++) {
                            if (this.uploadAttach[j].name === this.attachments[i].fileName) {
                                this.uploadAttach.splice(j--, 1)
                            }
                        }
                        this.attachments.splice(i--, 1)
                    } else if (file.id !== undefined && file.id === this.attachments[i].id) {
                        if (attachIds !== '') {
                            attachIds += ',' + this.attachments[i].id
                        } else {
                            attachIds = this.attachments[i].id
                        }
                    }
                } else if (this.attachments[i].checked) {
                    if (this.attachments[i].file !== undefined) {
                        for (let j = 0; j < this.uploadAttach.length; j++) {
                            if (this.uploadAttach[j].name === this.attachments[i].fileName) {
                                this.uploadAttach.splice(j--, 1)
                            }
                        }
                        this.attachments.splice(i--, 1)
                    } else if (this.attachments[i].forward) {
                        this.attachments.splice(i--, 1)
                    } else if (attachIds !== '') {
                        attachIds += ',' + this.attachments[i].id
                    } else {
                        attachIds = this.attachments[i].id
                    }
                }
            }

            if (attachIds !== '') {
                let deleteUrl = this.wfAttachUrl + '/delete'
                if (this.$vnode.context.wfInstance === undefined || this.$vnode.context.wfInstance.id === undefined) deleteUrl = this.wfAttachUrl + '/deleteAttach'// 非流程表单

                this.$confirm(`您是否确认删除选择的附件？`, '确认操作', { type: 'warning' }).then(() => {
                    this.$bus.emit('showDoingDialog')

                    this.$http({
                        method: 'DELETE',
                        contentType: 'application/x-www-form-urlencoded',
                        params: { attachIds: attachIds },
                        url: deleteUrl
                    }).then(res => {
                        this.$bus.emit('closeDoingDialog')
                        var _this = this
                        if (res.code === 'success') {
                            for (let i = 0; i < this.attachments.length; i++) {
                                if (file !== undefined) {
                                    if (file.id === this.attachments[i].id) {
                                        this.attachments.splice(i--, 1)
                                    }
                                } else if (this.attachments[i].checked) {
                                    this.attachments.splice(i--, 1)
                                }
                                if (_this.attachments[i])_this.attachments[i].checked = false
                            }
                            this.checkall = false
                            this.$message.success(res.message)
                            this.$forceUpdate()
                        } else {
                            this.$alert(res.message, '操作提示', { type: 'error' })
                        }
                    })
                })
            } else {
                this.checkall = false
                for (let i = 0; i < this.attachments.length; i++) {
                    this.attachments[i].checked = false
                }
            }
            this.$forceUpdate()
        },
        handleUploadChange(file, fileList) {
            // 不允许上传同名文件
            for (var j = 0; j < this.attachments.length; j++) {
                if (file.name === this.attachments[j].fileName && (this.attachments[j].fileType === this.attachsType || (!this.sameNameBodyfile && this.attachments[j].fileType === 'BODY'))) {
                    this.$message.error('文件“' + file.name + '”已存在，不允许上传命名文件。')
                    return
                }
            }

            this.uploadAttach = fileList

            const attach = {}
            attach.fileName = file.name
            attach.fileSize = formatFileSize(file.size)
            attach.fileType = this.attachsType
            attach.uploadBy = this.loginUser.personName
            attach.uploadTime = '待上传'
            attach.file = file
            attach.checked = false
            file.progress = 0
            this.attachments.push(attach)
            this.checkall = false

            this.$forceUpdate()
        },
        uploadWflowAttach($scope) {
            return new Promise(async resole => {
                const uploadAttach = []
                if ($scope.doNextAttach && $scope.doNextAttach.file !== undefined && $scope.doNextAttach.file !== null && $scope.doNextAttach.file.progress === 0) {
                    this.attachments.push($scope.doNextAttach)
                }
                const forwardAttachs = []
                this.attachments.forEach((attach, index) => {
                    if (attach.file != null && !attach.file.complete) {
                        if (attach.fileType === this.attachsType) {
                            attach.file.message = null
                            attach.file.fileType = attach.fileType || this.attachsType
                            attach.uploadIndex = index
                            uploadAttach.push(attach)
                        }
                    } else if (attach.forward) {
                        forwardAttachs.push(attach)
                    }
                })

                if (forwardAttachs.length > 0) {
                    $scope.wfInstance.passenger.forwardAttachs = forwardAttachs
                }

                // 上传文件
                const _this = this
                async function uploadAttachFile(attach) {
                    const file = attach.file
                    const config = {
                        onUploadProgress: progressEvent => {
                            const complete = (progressEvent.loaded / progressEvent.total * 100 | 0)
                            _this.$set(file, 'progress', complete)
                            _this.$set(attach, 'file', file)
                            _this.$forceUpdate()
                        }
                    }
                    let module = $scope.wfInstance.module

                    if (module === undefined) {
                        module = $scope.moduleCode || _this.wfAttachUrl.split('/')[1]
                    }

                    var reqData = { module: module, busiDataId: $scope.vo.id, attachsName: encodeURI(file.name), attachsType: file.fileType, attachsSize: file.size, bodyDocId: $scope.wfInstance.bodyDocId, clientType: 'uploader', uploadIndex: attach.uploadIndex || 0 }
                    if (attach.fileType === 'DONEXT') {
                        // 代办佐证材料
                        reqData.uploadBy = attach.uploadBy
                    }

                    let uploadUrl = _this.wfAttachUrl + '/upload'
                    if (_this.$vnode.context.moduleInfo && _this.$vnode.context.moduleInfo.uploadAttach) {
                        uploadUrl = _this.$vnode.context.moduleInfo.uploadAttach
                    }
                    const uploadRst = await _this.$wfEngine.upload(_this, uploadUrl, file.raw, reqData, config)
                    return uploadRst
                }

                // 先上传正文
                if ($scope.bodyfile && $scope.bodyfile.file !== undefined && $scope.bodyfile.file !== null && $scope.bodyfile.file.progress === 0) {
                    const bodyfile = $scope.bodyfile
                    bodyfile.file.message = null
                    bodyfile.file.fileType = bodyfile.fileType || this.attachsType
                    const resp = await uploadAttachFile(bodyfile)

                    if (resp.code === 'success') {
                        bodyfile.file.complete = true

                        let uploadBodyfile = null
                        resp.body.uploadAttachList.forEach(attach => {
                            this.attachments.push(attach)

                            if (attach.fileName.indexOf('.pdf') || attach.fileName.indexOf('.ofd')) {
                                // $scope.$set($scope, 'bodyfile', attach),浏览器刷新
                                uploadBodyfile = attach
                                $scope.bodyfile = attach

                                if (typeof $scope.vo.flBodyFilename !== 'undefined') {
                                    $scope.vo.flBodyFilename = attach.fileName
                                }
                            }
                        })

                        $scope.wfInstance.haveDoc = 2
                        if (uploadBodyfile.originalName.indexOf($scope.wfInstance.bodyDocId) === -1) {
                            $scope.wfInstance.bodyDocId = uploadBodyfile.originalName.split('\.')[0]
                        }

                        if (typeof $scope.vo.flBodyFilename !== 'undefined' && ($scope.vo.flBodyFilename === null || $scope.vo.flBodyFilename === '')) {
                            $scope.vo.flBodyFilename = bodyfile.fileName
                        }

                        if (bodyfile.fileName.indexOf('.doc') === -1 && $scope.commandBar) {
                            $scope.commandBar.forEach(btn => {
                                if (btn.btnCode === 'btnOpenWordClick' || btn.btnCode === 'btnModifyFlTypeClick') {
                                    btn.btnShow = false
                                }
                            })
                        }

                        if (uploadAttach.length === 0) resole({ code: 'success', message: '文件正文上传成功！' })
                    } else {
                        bodyfile.file.status = 'failure'
                        bodyfile.file.message = resp.message
                        if (uploadAttach.length === 0) resole(resp)
                    }
                }

                if (uploadAttach.length === 0) {
                    if (this.isRequired === 1 && !this.hasAttachment) {
                        this.$alert('请选择需要上传的附件！', '操作提示', { type: 'warning' })
                    } else {
                        resole({ code: 'success', message: '没有待上传附件' })
                    }
                }
                // 上传附件
                uploadAttach.forEach(async(attach, index) => {
                    const uploadRst = await uploadAttachFile(attach)
                    const file = attach.file
                    if (uploadRst.code === 'success') {
                        file.complete = true
                        // 检查是否全部上传成功
                        var complete = true
                        _this.attachments.forEach((iattach, iindex) => {
                            if (file === iattach.file) {
                                if (uploadRst.body.uploadAttachList.length === 2) {
                                    ($scope.attachments || $scope.vo.passenger.attachments || this.attachments).splice(iindex, 1, uploadRst.body.uploadAttachList[0], uploadRst.body.uploadAttachList[1])
                                } else {
                                    ($scope.attachments || $scope.vo.passenger.attachments || this.attachments).splice(iindex, 1, uploadRst.body.uploadAttachList[0])
                                }

                                if (iattach.fileType === 'DONEXT') {
                                    $scope.$set($scope, 'doNextAttach', uploadRst.body.uploadAttachList[0])
                                }
                            }
                            if (iattach.fileType === this.attachsType && iattach.file && iattach.file.complete !== true) {
                                complete = false
                            }
                        })
                        if (complete) {
                            resole({ code: 'success', message: '附件全部上传成功' })
                        }
                    } else {
                        file.status = 'failure'
                        file.message = uploadRst.message
                        resole(uploadRst)

                        this.$forceUpdate()
                    }
                })
            })
        },
        handleUploadError(err, file, fileList) {
            // this.uploading = false
            this.$message({
                showClose: true,
                message: err.message,
                type: 'error',
                dangerouslyUseHTMLString: true
            })
        },
        handleFileDownload(downType) {
            let attachIds = ''
            for (let i = 0; i < this.attachments.length; i++) {
                var attach = this.attachments[i]

                if (attach.checked || (downType === 'all' && attach.file === undefined)) {
                    if (attach.file != null) {
                        this.$alert('未上传的本地文件不支持另存！', '操作提示', { type: 'error' })
                        return
                    } else {
                        attachIds += ',' + attach.id
                    }
                }
            }

            if (attachIds !== '') {
                let downUrl = process.env.VUE_APP_BASE_API + '/' + this.wfAttachUrl + '/downloadById?inline=false&attachIds=' + attachIds.substring(1)
                if (this.batchSaveNamefield !== '') {
                    if (this.vo[this.batchSaveNamefield] === undefined) {
                        downUrl += '&saveAs=' + encodeURI(this.batchSaveNamefield)
                    } else {
                        downUrl += '&saveAs=' + encodeURI(this.vo[this.batchSaveNamefield])
                    }
                }
                downUrl += '&httpPort=' + location.port
                window.open(downUrl)
            } else if (downType === 'all') {
                this.$alert('没有可下载的附件。', '操作提示', { type: 'warning' })
            } else {
                this.$alert('请选择需要另存的附件。', '操作提示', { type: 'warning' })
            }
        },
        handleOneFileDownload(row) {
            let downUrl = process.env.VUE_APP_BASE_API + '/' + this.wfAttachUrl + '/downloadById?inline=false&attachIds=' + row.id
            downUrl += '&saveAs=' + encodeURI(row.fileName)
            downUrl += '&httpPort=' + location.port
            window.open(downUrl)
        },
        handleOpenEditor(attach) {
            this.$bus.emit('btnEditAttachClick', attach, this.onlineEditor)
        }
    }
}
</script>

<style scoped lang="scss">
@import "~@/wapp/common/styles/variables.scss";

.el-form{
    margin-top:20px;

    .svg-icon{
        margin: 0 5px;
    }
    .el-button{
        padding: 7px 5px;
    }
    .el-button:active{
        color: #606266
    }
    .el-button + .el-button{
        margin-left: 0px;
    }
    .el-link{
        line-height: 20px;
        color: $light-blue;
    }
    .is-disabled {
        color: #c4c5c7!important;
    }
    .fileHovering{
        background:rgb(165,196,93);
    }
    .fileHovering table{
        opacity: 0.5;
    }
    /deep/ .attach-name {
        max-width: 100%;
        span {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
    }
}

.attach-row{
    padding-top:5px;
    padding-bottom: 5px;
    line-height:21px;
}

.no-attachments{
    height:50px;line-height:20px;
}
.drag-handler{
    cursor: move;
}
/deep/ .atach-draggable .sortable-chosen{
    background: #F5F7FA;
}
</style>
